<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :md="6" :sm="12">
            <a-form-item :label="$t('账号')">
              <j-input :placeholder="$t('请输入账号')" v-model="queryParam.username"></j-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8">
            <a-form-item :label="$t('性别')">
              <a-select v-model="queryParam.sex" :placeholder="$t('请选择性别')">
                <a-select-option value="">{{ $t('请选择') }}</a-select-option>
                <a-select-option value="1">{{ $t('男') }}</a-select-option>
                <a-select-option value="2">{{ $t('女') }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :md="6" :sm="8">
              <a-form-item :label="$t('真实名字')">
                <a-input :placeholder="$t('请输入真实名字')" v-model="queryParam.realname"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-item :label="$t('手机号码')">
                <a-input :placeholder="$t('请输入手机号')" v-model="queryParam.phone"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-item :label="$t('用户状态')">
                <a-select v-model="queryParam.status" :placeholder="$t('请选择')">
                  <a-select-option value="">{{ $t('请选择') }}</a-select-option>
                  <a-select-option value="1">{{ $t('正常') }}</a-select-option>
                  <a-select-option value="2">{{ $t('冻结') }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24" v-if="!tenantId">
              <a-form-item :label="$t('门店')">
                <a-select v-model="queryParam.tenantId">
                  <a-select-option v-for="(item, i) in shops" :key="i" :value="item.value"
                    >{{ item.title }}<span v-if="item.value != ''">（{{ item.value }}）</span></a-select-option
                  >
                </a-select>
              </a-form-item>
            </a-col>
          </template>
          <a-col :md="6" :sm="8">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">{{ $t('查询') }}</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">{{
                $t('重置')
              }}</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? $t('收起') : $t('展开') }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator" style="border-top: 5px">
      <a-button v-has="'SystemUserController:add'" @click="handleAdd" type="primary" icon="plus">{{ $t('添加用户') }}</a-button>
      <a-button v-has="'OverSysUserController:export'" type="primary" icon="download" :loading="exloading" @click="handleExportXls($t('用户管理'))">{{
        $t('导出')
      }}</a-button>
      <!-- <a-upload
        name="file"
        :showUploadList="false"
        :multiple="false"
        :headers="tokenHeader"
        :action="importExcelUrl"
        @change="handleImportExcel"
      >
        <a-button type="primary" icon="import">{{ $t('导入') }}</a-button>
      </a-upload> -->
      <j-third-app-button
        biz-type="user"
        :selected-row-keys="selectedRowKeys"
        syncToApp
        syncToLocal
        @sync-finally="onSyncFinally"
      />
      <!-- <a-button type="primary" icon="hdd" @click="recycleBinVisible = true">{{ $t('回收站') }}</a-button> -->
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay" @click="handleMenuClick">
          <a-menu-item key="1">
            <a-icon type="delete" @click="batchDel" />
            {{ $t('删除') }}
          </a-menu-item>
          <a-menu-item key="2">
            <a-icon type="lock" @click="batchFrozen('2')" />
            {{ $t('冻结') }}
          </a-menu-item>
          <a-menu-item key="3">
            <a-icon type="unlock" @click="batchFrozen('1')" />
            {{ $t('解冻') }}
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">
          {{ $t('批量操作') }}
          <a-icon type="down" />
        </a-button>
      </a-dropdown>
      <j-super-query :fieldList="superQueryFieldList" @handleSuperQuery="handleSuperQuery" />
      <a-button type="primary" v-has="'UserList:settings'" @click="handleSettings">{{ $t('运营设置') }}</a-button>
    </div>

    <!-- table区域-begin -->
    <div>
      <!-- <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <i class="anticon anticon-info-circle ant-alert-icon"></i>
        <i18n path="selected-items" tag="span">
          <a place="items" style="font-weight: 600">{{ selectedRowKeys.length }}</a>
        </i18n>
        <a style="margin-left: 24px" @click="onClearSelected">{{ $t('清空') }}</a>
      </div> -->

      <a-table
        ref="table"
        bordered
        size="middle"
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        @change="handleTableChange"
      >
        <template slot="avatarslot" slot-scope="text, record">
          <div class="anty-img-wrap">
            <a-avatar shape="square" :src="getAvatarView(record.avatar)" icon="user" />
          </div>
        </template>

        <span slot="action" slot-scope="text, record">
          <a v-has="'OverSysUserController:edit'" @click="handleBind(record)">{{ $t('账号绑定') }}</a>
          <a-divider v-has="'OverSysUserController:edit'" type="vertical" />
          <a v-has="'OverSysUserController:edit'" @click="handleEdit(record)">{{ $t('编辑') }}</a>
          <a-divider v-has="'OverSysUserController:edit'" type="vertical" />
          <a href="javascript:;" @click="handleDetail(record)">{{ $t('详情') }}</a>
          <a-divider v-has="'OverSysUserController:edit'" type="vertical" />
          <a v-has="'OverSysUserController:edit'" href="javascript:;" @click="handleChangePassword(record.username)">{{ $t('密码') }}</a>
          <a-divider
            v-has="'OverSysUserController:delete'"
            type="vertical"
            v-if="
              tenantId != record.username && record.username != 'administrator' && record.username != record.tenantId
            "
          />
          <a-popconfirm :title="$t('确定删除吗?')" @confirm="() => handleDelete(record.id, { username: record.username })">
            <a
              v-has="'OverSysUserController:delete'"
              v-if="
                tenantId != record.username && record.username != 'administrator' && record.username != record.tenantId
              "
              >{{ $t('删除') }}</a
            >
          </a-popconfirm>
          <a-divider
            v-has="'OverSysUserController:edit'"
            type="vertical"
            v-if="
              record.status == 1 &&
              tenantId != record.username &&
              record.username != 'administrator' &&
              record.username != record.tenantId
            "
          />
          <a-popconfirm :title="$t('确定冻结吗?')" @confirm="() => handleFrozen(record.id, 2, record.username)">
            <a
              v-has="'OverSysUserController:edit'"
              v-if="
                record.status == 1 &&
                tenantId != record.username &&
                record.username != 'administrator' &&
                record.username != record.tenantId
              "
              >{{ $t('冻结') }}</a
            >
          </a-popconfirm>
          <a-divider v-has="'OverSysUserController:edit'" type="vertical" v-if="record.status == 2" />
          <a-popconfirm :title="$t('确定解冻吗?')" @confirm="() => handleFrozen(record.id, 1, record.username)">
            <a v-has="'OverSysUserController:edit'" v-if="record.status == 2">{{ $t('解冻') }}</a>
          </a-popconfirm>
        </span>
      </a-table>
    </div>
    <!-- table区域-end -->

    <user-modal ref="modalForm" @ok="modalFormOk"></user-modal>
    <user-bind-modal ref="bindModal" @ok="modalBindOk"></user-bind-modal>
    <password-modal ref="passwordmodal" @ok="passwordModalOk"></password-modal>
    <sys-user-agent-modal ref="sysUserAgentModal"></sys-user-agent-modal>
    <yarn-cert-out-captcha-modal ref="yarnModal" @ok="handleFrozenCallback"></yarn-cert-out-captcha-modal>
    <yarn-cert-out-captcha-modal ref="deleteYarnModal" @ok="handleDeleteCallback"></yarn-cert-out-captcha-modal>
    <!-- 用户回收站 -->
    <user-recycle-bin-modal :visible.sync="recycleBinVisible" @ok="modalFormOk" />
    <user-settings-modal ref="userSet"></user-settings-modal>
  </a-card>
</template>

<script>
import { getFileAccessHttpUrl, getAction, deleteAction } from '@/api/manage'
import { frozenBatch } from '@/api/api'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { initDictOptions } from '@/components/dict/JDictSelectUtil'
import UserModal from './modules/UserModal'
import PasswordModal from './modules/PasswordModal'
import SysUserAgentModal from './modules/SysUserAgentModal'
import UserRecycleBinModal from './modules/UserRecycleBinModal'
import UserBindModal from './modules/UserBindModal'
import JInput from '@/components/jeecg/JInput'
import JSuperQuery from '@/components/jeecg/JSuperQuery'
import JThirdAppButton from '@/components/jeecgbiz/thirdApp/JThirdAppButton'
import Vue from 'vue'
import YarnCertOutCaptchaModal from '@/views/setting/modules/YarnCertOutCaptchaModal'
import UserSettingsModal from './modules/UserSettingsModal'

export default {
  name: 'UserList',
  mixins: [JeecgListMixin],
  components: {
    JThirdAppButton,
    SysUserAgentModal,
    UserModal,
    PasswordModal,
    UserBindModal,
    JInput,
    UserRecycleBinModal,
    JSuperQuery,
    YarnCertOutCaptchaModal,
    UserSettingsModal
  },
  data() {
    return {
      description: '这是用户管理页面',
      queryParam: {},
      recycleBinVisible: false,
      columns: [
        {
          title: this.$t('门店编码'),
          align: 'center',
          sorter: true,
          dataIndex: 'tenantId',
        },
        {
          title: this.$t('门店名称'),
          align: 'center',
          dataIndex: 'tenantId_dictText',
          customRender: (t, r) => {
            if (!r.tenantId) {
              return this.$t('总部')
            }
            return t
          },
        },
        {
          title: this.$t('用户账号'),
          align: 'center',
          dataIndex: 'username',
          width: 120,
          sorter: true,
        },
        {
          title: this.$t('用户姓名'),
          align: 'center',
          width: 100,
          dataIndex: 'realname',
        },
        {
          title: this.$t('头像'),
          align: 'center',
          width: 120,
          dataIndex: 'avatar',
          scopedSlots: { customRender: 'avatarslot' },
        },

        {
          title: this.$t('性别'),
          align: 'center',
          width: 80,
          dataIndex: 'sex_dictText',
          sorter: true,
        },
        {
          title: this.$t('生日'),
          align: 'center',
          width: 100,
          dataIndex: 'birthday',
        },
        {
          title: this.$t('手机号码'),
          align: 'center',
          width: 100,
          dataIndex: 'phone',
        },
        {
          title: this.$t('所属角色'),
          align: 'center',
          width: 180,
          dataIndex: 'userRolesSet',
          customRender: function (text) {
            if (text) {
              let aa = ''
              aa = text[0]
              if (text.length > 1) {
                for (var i = 1; i < text.length; i++) {
                  aa = aa + '，' + text[i]
                }
              }
              return aa
            }
          },
        },
        {
          title: this.$t('状态'),
          align: 'center',
          width: 80,
          dataIndex: 'status_dictText',
        },
        {
          title: this.$t('操作'),
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' },
          align: 'center',
          width: 240,
        },
      ],
      superQueryFieldList: [
        { type: 'input', value: 'username', text: this.$t('用户账号') },
        { type: 'input', value: 'realname', text: this.$t('用户姓名') },
        { type: 'select', value: 'sex', dbType: 'int', text: this.$t('性别'), dictCode: 'sex' },
      ],
      url: {
        syncUser: '/act/process/extActProcess/doSyncUser',
        list: '/system/user/list',
        delete: '/sys/user/delete',
        deleteBatch: '/sys/user/deleteBatch',
        exportXlsUrl: '/sys/user/exportXls',
        importExcelUrl: 'sys/user/importExcel',
      },
      tenantId: Vue.ls.get('TENANT_ID'),
      shops: [],
      queryParam: {
        tenantId: '',
      },
      delCallback: this.delCallbacks
    }
  },
  created() {
    if (!this.tenantId) {
      initDictOptions('bis_shop,name,code').then((res) => {
        if (res.success) {
          this.shops = res.result
          this.shops.unshift({ value: '', title: this.$t('全部') })
        }
      })
    }
    if (this.tenantId) {
      this.columns = this.columns.filter((o) => {
        return o.dataIndex != 'tenantId' && o.dataIndex != 'tenantId_dictText'
      })
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {
    handleSettings(){
      this.$refs.userSet.show()
    },
    modalBindOk(){
      this.loadData(this.ipagination.current)
    },
    handleBind(record) {
      getAction('/bis/bisSysParameter/queryByName', { name: 'appletAppId' }).then((res) => {
        if (res.success) {
          this.$refs.bindModal.edit(record)
        }else{
          this.$message.warning(this.$t('该功能需要绑定小程序，请先开通小程序。'))
        }
      })
    },
    getAvatarView: function (avatar) {
      return getFileAccessHttpUrl(avatar)
    },
    batchFrozen: function (status) {
      let that = this
      if (that.selectedRowKeys.length <= 0) {
        that.$message.warning(that.$t('请选择一条记录'))
        return false
      } else {
        let ids = ''
        let isAdmin = false
        that.selectionRows.forEach(function (row) {
          if (row.username == 'admin') {
            isAdmin = true
          }
        })
        if (isAdmin) {
          that.$message.warning(that.$t('管理员账号不允许此操作,请重新选择'))
          return
        }
        that.selectedRowKeys.forEach(function (val) {
          ids += val + ','
        })
        that.$confirm({
          title: that.$t('确认操作'),
          content: that.$t('是否') + (status == 1 ? that.$t('解冻') : that.$t('冻结')) + that.$t('选中账号?'),
          okText: this.$t("确定"),
          cancelText: this.$t("取消"),
          onOk: function () {
            frozenBatch({ ids: ids, status: status }).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadData()
                that.onClearSelected()
              } else {
                that.$message.warning(res.message)
              }
            })
          },
        })
      }
    },
    handleMenuClick(e) {
      if (e.key == 1) {
        this.batchDel()
      } else if (e.key == 2) {
        this.batchFrozen(2)
      } else if (e.key == 3) {
        this.batchFrozen(1)
      }
    },
    
    handleFrozen: function (id, status, username) {
      let that = this
      //TODO 后台校验管理员角色
      if ('admin' == username) {
        that.$message.warning(that.$t('管理员账号不允许此操作'))
        return
      }
      frozenBatch({ ids: id, status: status }).then((res) => {
        if (res.success) {
          that.$message.success(res.message)
          that.loadData()
        } else if(res.code == 750){ // 需要验证码
          //认证
          let param= {id:id,status:status};
          that.$refs.yarnModal.show(param);
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    handleFrozenCallback: function (result) {
      let that = this
      frozenBatch({ ids: result.id, status: result.status,captcha:result.captcha }).then((res) => {
        if (res.success) {
          that.$message.success(res.message)
          that.$refs.yarnModal.close();
          that.loadData()
        } else {
          that.$message.warning(res.message)
        }
      })
    },

    handleDelete: function (id, arg) {
      //认证
      let param= {id:id,arg:arg};
      var that = this;
      deleteAction(that.url.delete, { id: id }).then((res) => {
        if (res.success) {
          //重新计算分页问题
          that.reCalculatePage(1)
          that.$message.success(res.message);
          that.loadData();
          if (that.delCallback != null && that.delCallback != undefined) {
            that.delCallback(arg);
          }
        } else if(res.code == 750){ // 需要验证码
          //认证
          that.$refs.deleteYarnModal.show(param);
        } else {
          that.$message.warning(res.message);
        }
      });
    },
    handleDeleteCallback: function (result) {
      let that = this
      deleteAction(that.url.delete, { id: result.id,captcha:result.captcha }).then((res) => {
        if (res.success) {
          //重新计算分页问题
          that.reCalculatePage(1)
          that.$message.success(res.message);
          that.$refs.deleteYarnModal.close();
          that.loadData();
          if (that.delCallback != null && that.delCallback != undefined) {
            that.delCallback(arg);
          }
        } else {
          that.$message.warning(res.message);
        }
      });
    },
    handleChangePassword(username) {
      this.$refs.passwordmodal.show(username)
    },
    handleAgentSettings(username) {
      this.$refs.sysUserAgentModal.agentSettings(username)
      this.$refs.sysUserAgentModal.title = this.$t('用户代理人设置')
    },
    passwordModalOk() {
      //TODO 密码修改完成 不需要刷新页面，可以把datasource中的数据更新一下
    },
    onSyncFinally({ isToLocal }) {
      // 同步到本地时刷新下数据
      if (isToLocal) {
        this.loadData()
      }
    },
    searchReset() {
      this.queryParam = {
        tenantId: '',
      }
      this.searchQuery()
    },
    delCallbacks(record){
      let userList = []
      let obj = JSON.parse(plugin.getData('C:\\ProgramData\\leyudm\\Manage\\user.json', 'remUser', localStorage.getItem('remUser'))) || {}
      let rememberMe = obj.rememberMe || false
      if (rememberMe) {
        if (localStorage.getItem('username') != null) {
          userList = JSON.parse(localStorage.getItem('username'))
        }
        let str = plugin.getData('C:\\ProgramData\\leyudm\\Manage\\user.json', 'username', localStorage.getItem('username'))
        if (str) {
          userList = JSON.parse(str)
        }
        let i = userList.indexOf(record.username)
        if (i > -1) {
          userList.splice(i, 1)
        }
      }
      localStorage.setItem('username', JSON.stringify(userList))
      plugin.setData('C:\\ProgramData\\leyudm\\Manage\\user.json', 'username', JSON.stringify(userList))
    }
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>